package JDBC;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2022-07-20
 * Time: 15:46
 */
public class JDBCSelect {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/practice?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        Connection connection=dataSource.getConnection();
        String sql="select * from student";
        PreparedStatement statement=connection.prepareStatement(sql);
        //executeQuery得到的是一个ResultSet对象，可以把这个对象视为一个临时表
        ResultSet resultSet=statement.executeQuery();
        //resultSet类似一个迭代器
        //next没有到达末尾返回true，不然返回false
        while(resultSet.next()){
            //通过ResultSet里的getxxx方法取数据
            int id=resultSet.getInt("id");//括号里为列名
            String name=resultSet.getString("name");
            System.out.println(id+" "+name);
        }
        resultSet.close();
        statement.close();
        connection.close();
    }
}
